// 云函数入口文件
const cloud = require("wx-server-sdk");
const CloudBase = require("@cloudbase/manager-node");
const isUndefined = require("lodash/isUndefined");

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV, //API 调用都保持和云函数当前所在环境一致
});

const db = cloud.database({
  env: cloud.DYNAMIC_CURRENT_ENV,
});

const { storage } = new CloudBase({
  envId: cloud.DYNAMIC_CURRENT_ENV, // 云开发环境ID，进入云开发的时候可以从右上角进行复制
});

const ERROR_MSG = {
  500: "服务器错误",
  401: "登录过期",
  404: "未找到资源",
  4001: "重复提交",
};

class CustomError extends Error {
  constructor(code, msg) {
    super();
    this.code = code || 500;
    this.msg = msg || ERROR_MSG[code] || "unknown error";
  }

  getCodeMsg() {
    return {
      code: this.code,
      msg: this.msg,
    };
  }
}

const TcbRouter = require("tcb-router");
const _ = db.command;

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  const app = new TcbRouter({ event });
  // return await db.collection("homeList").get();

  // 适用于所有的路由
  app.use(async (ctx, next) => {
    //适用于所有的路由
    ctx.data = {}; //声明data为一个对象
    try {
      ctx.body = {};
      ctx.body.code = 0;
      await next();
    } catch (err) {
      console.log(err, "err".repeat(10));
      console.log(ctx);
      if (err instanceof CustomError) {
        const res = err.getCodeMsg();
        ctx.body = {};
        ctx.body.code = res.code || 500;
        ctx.body.msg = res.msg;
      } else if (err instanceof Error) {
        console.log(err);
        ctx.body = {};
        ctx.body.code = 500;
        ctx.body.msg = err.message;
      } else if (typeof err === "string") {
        ctx.body = {};
        ctx.body.code = 500;
        ctx.body.msg = err;
      } else {
        ctx.body = {};
        ctx.body.code = res.code || 500;
        ctx.body.msg = res.msg;
      }
    }
  });

  //添加用户
  app.router("addUser", async (ctx, next) => {
    const { nickName, avatar } = event;
    try {
      await db
        .collection("user")
        .where({
          openId: wxContext.OPENID,
        })
        .get()
        .then((res) => {
          //判断内容是否为空
          if (res.data.length < 1) {
            db.collection("user").add({
              data: {
                //插入数据
                openId: wxContext.OPENID,
                nickName,
                avatar,
              },
            });
          } else {
            ctx.body = {
              openIDEXIST: true,
            };
          }
        });
    } catch (error) {
      if (error instanceof Error) {
        throw new CustomError(500, error.message);
      } else if (typeof error === "string") {
        throw new CustomError(500, error);
      }
    }
  });

  //添加用户实名信息
  app.router("addReal", async (ctx, next) => {
    try {
      const { realName, identityId, phone } = event.data;
      await db
        .collection("user")
        .where({
          openId: wxContext.OPENID,
        })
        .update({
          data: {
            realName,
            identityId,
            phone,
          },
        });
    } catch (error) {
      if (error instanceof Error) {
        throw new CustomError(500, error.message);
      } else if (typeof error === "string") {
        throw new CustomError(500, error);
      }
    }
  });

  //获取版权信息
  app.router("addCopyRight", async (ctx, next) => {
    try {
      const {
        workName,
        workType,
        creativeNature,
        rightAcquisitionMode,
        attributionOfWorks,
        content,
        ownershipOfRights,
        userCopyRightType,
        copyrightchart,
      } = event.data;
      await db.collection("copyRight").add({
        data: {
          _createTime: Date.now(),
          openId: wxContext.OPENID,
          userCopyRightType,
          workName,
          workType,
          creativeNature,
          rightAcquisitionMode,
          attributionOfWorks,
          content,
          ownershipOfRights,
          copyrightchart,
          // enumerate,
        },
      });
    } catch (error) {
      if (error instanceof Error) {
        throw new CustomError(500, error.message);
      } else if (typeof error === "string") {
        throw new CustomError(500, error);
      }
    }
  });

  //获取代理人版权信息
  // app.router("getCopyRight", async (ctx, next) => {
  //   try {
  //     const {
  //       workName,
  //       workType,
  //       creativeNature,
  //       rightAcquisitionMode,
  //       attributionOfWorks,
  //       content,
  //       ownershipOfRights,
  //       userCopyRightType,
  //       copyrightchart,
  //     } = event.data;
  //     await db.collection("copyRight").add({
  //       data: {
  //         _createTime: Date.now(),
  //         openId: wxContext.OPENID,
  //         userCopyRightType,
  //         workName,
  //         workType,
  //         creativeNature,
  //         rightAcquisitionMode,
  //         attributionOfWorks,
  //         content,
  //         ownershipOfRights,
  //         copyrightchart,
  //         // enumerate,
  //       },
  //     });
  //   } catch (error) {
  //     if (error instanceof Error) {
  //       throw new CustomError(500, error.message);
  //     } else if (typeof error === "string") {
  //       throw new CustomError(500, error);
  //     }
  //   }
  // });

  //我的申请
  app.router("myApplication", async (ctx, next) => {
    try {
      await db
        .collection("copyRight")
        .where({
          openId: wxContext.OPENID,
        })
        .get()
        .then((res) => {
          ctx.body = {
            data: res.data,
          };
        });
    } catch (error) {
      if (error instanceof Error) {
        throw new CustomError(500, error.message);
      } else if (typeof error === "string") {
        throw new CustomError(500, error);
      }
    }
  });

  //查询
  app.router("search", async (ctx, next) => {
    const { key } = event.data;
    try {
      await db
        .collection("copyRight")
        .where({
          workName: db.RegExp({
            regexp: ".*" + key + ".*",
            options: "i",
          }),
        })
        .get()
        .then((res) => {
          ctx.body = {
            data: res.data,
          };
        });
    } catch (error) {
      if (error instanceof Error) {
        throw new CustomError(500, error.message);
      } else if (typeof error === "string") {
        throw new CustomError(500, error);
      }
    }
  });

  //用户数量，
  app.router("getCount", async (ctx, next) => {
    try {
      const countUser = await db.collection("user").count();
      const countCopyRight = await db.collection("copyRight").count();
      ctx.body = {
        countUser,
        countCopyRight,
        wxContext,
      };
    } catch (error) {
      if (error instanceof Error) {
        throw new CustomError(500, error.message);
      } else if (typeof error === "string") {
        throw new CustomError(500, error);
      }
    }
  });

  //科普表
  app.router("getScience", async (ctx, next) => {
    try {
      let limitNum = 10;
      let skipNum = 0;
      if (!isUndefined(event.limit)) {
        limitNum = isNumber(event.limit) ? event.limit : limitNum;
      }
      // 分页参数构造
      if (!isUndefined(event.page)) {
        skipNum = (event.page - 1) * limitNum;
      }
      await db
        .collection("science")
        .orderBy("_createTime", "desc")
        .limit(limitNum)
        .skip(skipNum)
        .get()
        .then((res) => {
          // science = science.concat(res.data)
          ctx.body = {
            data: res.data,
          };
        });
    } catch (error) {
      if (error instanceof Error) {
        throw new CustomError(500, error.message);
      } else if (typeof error === "string") {
        throw new CustomError(500, error);
      }
    }
  });

  //新增商品收藏表
  app.router("addSaleCollect", async (ctx, next) => {
    try {
      const openId = wxContext.OPENID;
      const { _id } = event.data;
      const data = await db
        .collection("sale")
        .where({ _id })
        .field({ openId: true })
        .get()
        .then((res) => {
          return res.data;
        });
      if (data[0].openId.indexOf(openId) > -1) {
        db.collection("sale")
          .where({
            _id,
          })
          .update({
            data: {
              openId: _.pull(openId),
            },
          });
      } else {
        db.collection("sale")
          .where({
            _id,
          })
          .update({
            data: {
              openId: _.push(openId),
            },
          });
      }
    } catch (error) {
      if (error instanceof Error) {
        throw new CustomError(500, error.message);
      } else if (typeof error === "string") {
        throw new CustomError(500, error);
      }
    }
  });

  //删除商品收藏
  // app.router("removeSaleCollect", async (ctx, next) => {
  //   try {
  //     const openId = wxContext.OPENID
  //     const {_id} = event.data
  //     await db.collection('sale').where({
  //       _id:_id
  //     }).update({
  //       data:{
  //         openId:_.pull(openId)
  //       }
  //     })
  //   } catch (error) {
  //     if (error instanceof Error) {
  //       throw new CustomError(500, error.message);
  //     } else if (typeof error === "string") {
  //       throw new CustomError(500, error);
  //     }
  //   }
  // });

  //显示我的商品收藏
  app.router("getSaleCollect", async (ctx, next) => {
    try {
      const openId = wxContext.OPENID;
      await db
        .collection("sale")
        .where({ openId })
        .get()
        .then((res) => {
          ctx.body = {
            data: res.data,
          };
        });
    } catch (error) {
      if (error instanceof Error) {
        throw new CustomError(500, error.message);
      } else if (typeof error === "string") {
        throw new CustomError(500, error);
      }
    }
  });

  //详情商品显示
  app.router("getSaleContent", async (ctx, next) => {
    try {
      const { _id } = event;
      await db
        .collection("sale")
        .doc(_id)
        .get()
        .then((res) => {
          ctx.body = {
            data: res.data,
          };
        });
    } catch (error) {
      if (error instanceof Error) {
        throw new CustomError(500, error.message);
      } else if (typeof error === "string") {
        throw new CustomError(500, error);
      }
    }
  });

  //添加商品
  app.router("addSale", async (ctx, next) => {
    try {
      const { name, price, image } = event.data;
      await db.collection("sale").add({
        data: {
          name,
          price,
          image,
        },
      });
    } catch (error) {
      if (error instanceof Error) {
        throw new CustomError(500, error.message);
      } else if (typeof error === "string") {
        throw new CustomError(500, error);
      }
    }
  });

  //显示商店表
  app.router("getSale", async (ctx, next) => {
    try {
      let limitNum = 10;
      let skipNum = 0;
      if (!isUndefined(event.limit)) {
        limitNum = isNumber(event.limit) ? event.limit : limitNum;
      }
      // 分页参数构造
      if (!isUndefined(event.page)) {
        skipNum = (event.page - 1) * limitNum;
      }
      await db
        .collection("sale")
        .orderBy("create_time", "desc")
        .limit(limitNum)
        .skip(skipNum)
        .get()
        .then((res) => {
          ctx.body = {
            data: res.data,
            openid: wxContext.OPENID,
          };
          // sale = sale.concat(res.data)
        });
    } catch (error) {
      if (error instanceof Error) {
        throw new CustomError(500, error.message);
      } else if (typeof error === "string") {
        throw new CustomError(500, error);
      }
    }
  });

  //新增科普文章收藏
  app.router("addScienceCollect", async (ctx, next) => {
    try {
      const openId = wxContext.OPENID;
      const { _id } = event.data;
      const data = await db
        .collection("science")
        .where({ _id })
        .field({ openId: true })
        .get()
        .then((res) => {
          return res.data;
        });
      if (data[0].openId.indexOf(openId) > -1) {
        db.collection("science")
          .where({
            _id,
          })
          .update({
            data: {
              openId: _.pull(openId),
            },
          });
      } else {
        db.collection("science")
          .where({
            _id,
          })
          .update({
            data: {
              openId: _.push(openId),
            },
          });
      }
    } catch (error) {
      if (error instanceof Error) {
        throw new CustomError(500, error.message);
      } else if (typeof error === "string") {
        throw new CustomError(500, error);
      }
    }
  });

  //显示科普收藏
  app.router("getScienceCollect", async (ctx, body) => {
    try {
      const openId = wxContext.OPENID;
      await db
        .collection("science")
        .where({
          openId: openId,
        })
        .get()
        .then((res) => {
          ctx.body = {
            data: res.data,
          };
        });
    } catch (error) {
      if (error instanceof Error) {
        throw new CustomError(500, error.message);
      } else if (typeof error === "string") {
        throw new CustomError(500, error);
      }
    }
  });

  //新增代理人
  app.router("addAgent", async (ctx, next) => {
    const { fileList, thing } = event.data;
    try {
      await db.collection("agent").add({
        data: {
          fileList,
          thing,
          openId: wxContext.OPENID,
        },
      });
    } catch (error) {
      if (error instanceof Error) {
        throw new CustomError(500, error.message);
      } else if (typeof error === "string") {
        throw new CustomError(500, error);
      }
    }
  });

  //根据文章id查找文章内容
  app.router("searchArticleContent", async (ctx, next) => {
    const { _id } = event;
    try {
      await db
        .collection("science")
        .doc(_id)
        .get()
        .then((res) => {
          ctx.body = {
            data: res.data,
          };
        });
    } catch (error) {
      if (error instanceof Error) {
        throw new CustomError(500, error.message);
      } else if (typeof error === "string") {
        throw new CustomError(500, error);
      }
    }
  });

  //详情版权申请内容
  app.router("getApplication", async (ctx, next) => {
    try {
      const { _id } = event;
      await db
        .collection("copyRight")
        .doc(_id)
        .get()
        .then((res) => {
          ctx.body = {
            data: res.data,
          };
        });
    } catch (error) {
      if (error instanceof Error) {
        throw new CustomError(500, error.message);
      } else if (typeof error === "string") {
        throw new CustomError(500, error);
      }
    }
  });

  app.router("getFileZhuanli", async (ctx, next) => {
    const res = await storage.listDirectoryFiles("zhuanli/");
    ctx.body = {
      data: res,
    };
  });

  app.router("getFileBanquan", async (ctx, next) => {
    const res = await storage.listDirectoryFiles("zhuzuoquan/学生著作权/");
    ctx.body = {
      data: res,
    };
  });
  
  app.router("getFileBanquanjs", async (ctx, next) => {
    const res = await storage.listDirectoryFiles("zhuzuoquan/教师著作权/");
    ctx.body = {
      data: res,
    };
  });

  // return {
  //   event,
  //   openid: wxContext.OPENID,
  //   appid: wxContext.APPID,
  //   unionid: wxContext.UNIONID,
  // }
  return app.serve();
};
